<template>
  <div ref="editorDOM" style="height:100%;width:100%"></div>
</template>

<script>
  import CodeMirror from 'codemirror'
  // import './addons'

  const UIThemeOptions = ['base-theme', 'dark']
  const SyntaxThemeOptions = ['default', 'neo', 'eclipse', 'monokai', 'material']

  export default {
    components: {

    },
    props: {
      theme: { default: 'default' },
      tab: { type: Object }
    },
    data: function () {
      return {
        width: '100%',
        height: '100%',
        editor: {}
      }
    },
    computed: {
      themeSetting: function () {
        return {
          id: 'THEME',
          items: [
            {
              name: 'UI Theme',
              value: 'Light',
              options: UIThemeOptions
            },
            {
              name: 'Syntax Theme',
              value: 'default',
              options: SyntaxThemeOptions
            }
          ]
        }
      }
    },

    mounted() {
      const themeConfig = this.themeSetting.items[0].value.split('/').pop();
      const editor = this.editor = CodeMirror(this.$el, {
        theme: themeConfig,
        autofocus: true,
        lineNumbers: true,
        matchBrackets: true,
        autoCloseBrackets: true,
      });
      // @fixme:
      // related counterparts:
      // 1. IdeEnvironment.js
      // 2. commandBindings/file.js
      window.ide.editors[this.tab.id] = editor

      editor.setSize(this.width, this.height);
      // 2. prevent default codemirror dragover handler, so the drag-to-split feature can work
      //    but the default handler that open a file on drop is actually pretty neat,
      //    should make our drag feature compatible with it later
      editor.on('dragover', e => e.preventDefault())

      if (this.tab.content) {
        const body = this.tab.content.body;
        const modeInfo = this.getMode(this.tab);
        if (body) editor.setValue(body);
        if (modeInfo) {
          let mode = modeInfo.mode;
          if (mode === 'null') {
            editor.setOption('mode', mode)
          } else {
            require([`codemirror/mode/${mode}/${mode}.js`], () => editor.setOption('mode', mode));
          }
        }
      }
      editor.focus();
      editor.isFocused = editor.hasFocus; // little hack to make codemirror work with legacy interface
      // editor.on('change', this.onChange);
      // editor.on('focus', () => this.props.dispatch(TabActions.activateTab(tab.id)))
    }
  }

</script>
